% [ aEst,T2Est, NaEst, res] = T2FITTING(data, extra)

function [ aEst,T2Est, NaEst, res] = T2FITTING(data, extra)

%% Set the initial values for the search
try
    x0(2) =  extra.T1Init;
    x0(1) = max(data);
catch
    x0 = extra.x0;
end

%% Make sure data is a column vector
data = data(:);
extra.tVec = extra.tVec(:);

%% Do the fit
x = fminsearch( ...
    @(x)sum(abs( data-( x(1)*exp(-extra.tVec/x(2)) )).^2), ...
    x0,optimset('display','off'));

aEst = x(1);
NaEst = -x(1);
T2Est = x(2);

%% Compute the residual
modelValue = aEst*exp(-extra.tVec/T2Est);
res = ...
    1/sqrt(length(data))*norm(1 - modelValue./data);
% Corrcoef  = corrcoef(data, modelValue);
% R_2 = Corrcoef(1,2)^2;
% if(R_2 < 0.9 )
%     T2Est = NaN;
% end

